package com.zuiacsn.forum.service.impl;

import com.zuiacsn.forum.common.AppResult;
import com.zuiacsn.forum.common.ResultCode;
import com.zuiacsn.forum.dao.MessageMapper;
import com.zuiacsn.forum.dao.UserMapper;
import com.zuiacsn.forum.exception.ApplicationException;
import com.zuiacsn.forum.model.Board;
import com.zuiacsn.forum.model.User;
import com.zuiacsn.forum.service.IUserService;
import com.zuiacsn.forum.utils.MD5Util;
import com.zuiacsn.forum.utils.StringUtil;
import com.zuiacsn.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.transform.Result;
import java.util.Date;
import java.util.UUID;


@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    private MessageMapper messageMapper;

    /**
     * 创建普通用户
     * @param user
     */
    public void createNormalUser(User user) {
        // 1.判断非空
        if(user == null || StringUtil.isEmpty(user.getUsername()) || StringUtil.isEmpty(user.getNickname()
        ) || StringUtil.isEmpty(user.getPassword()) || StringUtil.isEmpty(user.getSalt())){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE.toString()));
        }

        // 2.根据用户名查询用户信息
        User exists = userMapper.selectByUserName(user.getUsername());
        // 2.1 判断用户名是否存在
        if(exists != null){
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS.toString()));
        }

        // 2.2 用户不存在,新增用户信息,设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        // 当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        // 2.3 插入数据库,动态插入
        // 返回受影响的行数
        int row = userMapper.insertSelective(user);
        if(row != 1){
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE.toString()));
        }
        log.info("新增用户成功 username="+user);
    }

    @Override
    public User selectByUserName(String username) {
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        // 1.非空检验
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE.toString()));
        }
        // 2. 按用户名查询用户信息
        User user = userMapper.selectByUserName(username);

        // 3. 对查询结果进行非空检验
        if(user == null){
            log.info(ResultCode.FAILED_LOGIN.toString()+ ", username = " + username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN.toString()));
        }

        // 4. 对密码做校验
        String salt = user.getSalt();
        String password_salt = MD5Util.md5Salt(password, salt);
        if(!user.getPassword().equals(password_salt)){
            log.info(ResultCode.FAILED_LOGIN.toString()+",密码错误 username = " + username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 登录成功,返回用户信息
        log.info("登录成功 username="+username);
        return user;
    }

    @Override
    public User selectById(Long id) {
        //非空检验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE.toString()));
        }
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    /**
     * 更新用户发帖数
     * @param id
     */
    @Override
    public void addOneArticleCountById(Long id) {
        // 非空检验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        User user = userMapper.selectByPrimaryKey(id);

        // 校验用户是否为空
        if(user == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        // 更新用户帖子数量:  用户帖子数量加1
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);

        if(row != 1){
            log.warn(ResultCode.FAILED.toString()+", 受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        // 非空检验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        User user = userMapper.selectByPrimaryKey(id);

        // 校验用户是否为空
        if(user == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        // 更新用户帖子数量:  用户帖子数量加1
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);
        if(updateUser.getArticleCount() == 0){
            updateUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString()+", 受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    /**
     * 修改用户信息
     * @param user
     */
    public void modifyInfo(User user) {
        // 非空检验
        if(user == null || user.getId() == null || user.getId() <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //校验用户是否存在
        User existUser = userMapper.selectByPrimaryKey(user.getId());
        if(existUser == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 定义一个标志位,校验所有参数是否为空,对每一个参数进行校验
        boolean check = false;
        User updateUser = new User();
        updateUser.setId(user.getId());

        // 校验用户名
        if(!StringUtil.isEmpty(user.getUsername()) && !user.getUsername().equals(existUser.getUsername())){
            // 判断是否有同名用户,如果有的话,不允许修改
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if(checkUser != null){
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }else{
                check = true;
                updateUser.setUsername(user.getUsername());
            }
        }

        // 校验昵称
        if(!StringUtil.isEmpty(user.getNickname()) && !user.getNickname().equals(existUser.getNickname())){
            check = true;
            updateUser.setNickname(user.getNickname());
        }

        //校验性别
        if(user.getGender() != null && user.getGender() != existUser.getGender()){
            check = true;
            updateUser.setGender(user.getGender());
        }

        // 校验邮箱
        if(!StringUtil.isEmpty(user.getEmail()) && !user.getEmail().equals(existUser.getEmail())){
            check = true;
            updateUser.setEmail(existUser.getEmail());
        }
        // 校验电话号码
        if(!StringUtil.isEmpty(user.getPhoneNum() )&& !user.getPhoneNum().equals(existUser.getPhoneNum())){
            check = true;
            updateUser.setPhoneNum(existUser.getPhoneNum());
        }

        if(!StringUtil.isEmpty(user.getRemark()) && !user.getRemark().equals(existUser.getRemark())){
            check = true;
            updateUser.setRemark(existUser.getRemark());
        }

        // 根据标志位判断是否可以执行sql语句
        if(!check){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 修改用户密码
     * @param id
     * @param newPassword
     * @param oldPassword
     */
    public void modifyPwd(Long id, String newPassword, String oldPassword) {
        // 非空校验
        if(id == null || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 校验用户是否存在
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null || user.getDeleteState() == 1){
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 校验老密码是否是数据库中的密码
        String password_salt = MD5Util.md5Salt(oldPassword, user.getSalt());
        if(!user.getPassword().equals(password_salt)){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

        // 生成新密码
        String salt = UUIDUtil.UUID_32();
        newPassword = MD5Util.md5Salt(newPassword, salt);

        // 构建更新对象
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setSalt(salt);
        updateUser.setPassword(newPassword);

        // 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString()+", 受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }



}
